package com.www.jpa.service;

import cn.hutool.core.codec.Base64;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.www.jpa.dao.BackupRecordRepository;
import com.www.jpa.entity.BackupRecord;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * .
 *
 * @author o_o
 * @date 2025-06-23
 */
@Service
@Transactional
@Slf4j
public class DatabaseBackupService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private BackupRecordRepository backupRecordRepository;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 执行多表备份
     * @param backupName 备份名称
     * @param tableNames 需要备份的表名列表
     * @return 备份记录ID
     */
    public Long performBackup(String backupName, List<String> tableNames) {
        try {
            // 1. 查询各表数据
            Map<String, List<Map<String, Object>>> tableDataMap = new LinkedHashMap<>();

            for (String tableName : tableNames) {
                List<Map<String, Object>> tableData = queryTableData(tableName);
                tableDataMap.put(tableName, tableData);
            }

            // 2. 转换为JSON
            String jsonData = objectMapper.writeValueAsString(tableDataMap);

            // 3. 保存备份记录
            BackupRecord record = new BackupRecord();
            record.setBackupName(backupName);
            record.setTablesIncluded(String.join(",", tableNames));
            record.setBackupTime(LocalDateTime.now());
            record.setDataJson(Base64.encode(jsonData));

            BackupRecord savedRecord = backupRecordRepository.save(record);
            return savedRecord.getId();
        } catch (Exception e) {
            log.error("备份失败", e);
            throw new RuntimeException("备份失败: " + e.getMessage(), e);
        }
    }

    /**
     * 查询表数据
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> queryTableData(String tableName) {
        String sql = "SELECT * FROM " + tableName;
        entityManager.clear();
        Query query = entityManager.createNativeQuery(sql);

        // 获取结果并转换为Map列表
        List<Object[]> results = query.getResultList();
        List<Map<String, Object>> dataList = new ArrayList<>();

        if (!results.isEmpty()) {
            // 获取列名
            List<String> columnNames = getColumnNames(tableName);

            for (Object[] row : results) {
                Map<String, Object> rowMap = new LinkedHashMap<>();
                for (int i = 0; i < columnNames.size(); i++) {
                    rowMap.put(columnNames.get(i), row[i]);
                }
                dataList.add(rowMap);
            }
        }

        return dataList;
    }

    /**
     * 获取表的列名
     */
    @SuppressWarnings("unchecked")
    private List<String> getColumnNames(String tableName) {
        // 不同数据库获取列名的SQL不同
        String sql;
        if (isOracleDatabase()) {
            sql = "SELECT column_name FROM all_tab_columns WHERE table_name = ?";
        } else {
            sql = "SELECT column_name FROM information_schema.columns WHERE table_name = ?";
        }

        Query query = entityManager.createNativeQuery(sql)
                .setParameter(1, tableName.replace("`", ""));
        return query.getResultList();
    }

    /**
     * 判断是否为Oracle数据库
     */
    private boolean isOracleDatabase() {
        return false;
    }
}